package repo

import (
	"app-box/api_error"

	"gorm.io/gorm"
)

type BaseRepo struct {
	DB       *gorm.DB
	isCommit bool
}

func (repo *BaseRepo) Begain() {
	repo.DB = repo.DB.Begin()
	if err := repo.DB.Error; err != nil {
		panic(api_error.DataBaseError(err))
	}
	repo.isCommit = false
}

func (repo *BaseRepo) RollbackIfNeed() {
	if repo.isCommit { // 已经提交，不再回滚
		return
	}
	if err := repo.DB.Rollback().Error; err != nil {
		panic(api_error.DataBaseError(err))
	}
}

func (repo *BaseRepo) Commit() {
	if err := repo.DB.Commit().Error; err != nil {
		panic(api_error.DataBaseError(err))
	}
	repo.isCommit = true
}
